import ResManager from "../../core/ResManager";
import NodePool from "../../core/NodePool";
import JewelData from "./JewelData";
import EventManager from "../../core/EventManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Jewel extends cc.Component {

    @property({ type: cc.Sprite, tooltip: CC_DEV && '背景图' })
    public background: cc.Sprite = null;

    //类型
    private m_type: number;
    //坐标
    private m_x: number;
    private m_y: number;
    private m_isSwaping: boolean; //是否正在交换
    private m_isCrushing: boolean; //是否正在消除 

    public getType(): number { return this.m_type; }
    public getX(): number { return this.m_x; }
    public getY(): number { return this.m_y; }

    public setX(x: number): void { this.m_x = x; }
    public setY(y: number): void { this.m_y = y; }

    public isSwaping(): boolean { return this.m_isSwaping; }
    public isCrushing(): boolean { return this.m_isCrushing; }

    public setSwapingState(state: boolean): void { this.m_isSwaping = state; }

    //消除
    public crush(): void {
        //加分
        JewelData.ins().score++;
        this.m_isCrushing = true;
        cc.tween(this.node)
            .to(0.2, { scale: 0.1, opacity: 0 }, { easing: 'backIn' })
            .call(() => {
                //销毁
                this.m_isCrushing = false;

                //返回对象池前把属性设置回去
                this.node.scale = 1.0;
                this.node.opacity = 255;
                NodePool.backObjPool(NodePool.mPool, { name: "jewels", prefab: this.node });
                // this.node.destroy();//直接销毁
                EventManager.emit('updateScore');
            })
            .start();
    }

    public init(type: number, x: number, y: number): void {
        this.m_type = type;
        this.m_x = x;
        this.m_y = y;
        this.m_isSwaping = false;
        this.m_isCrushing = false;
        this.background.spriteFrame = ResManager.ins().getRes('jewel' + type);
    }

    public setPosition(x: number, y: number): void {
        this.node.setPosition(x, y);
    }
}